//
//  AddPersonViewController.m
//  SoundPill
//
//  Created by 宋旭东 on 15/3/13.
//  Copyright (c) 2015年 宋旭东. All rights reserved.
//

#import "AddPersonViewController.h"
#import "PersonBtn.h"
#import "Edit_addTextView.h"
#import "FXBlurView.h"
@interface AddPersonViewController ()<UIScrollViewDelegate>
{
    NSInteger oldTag;
    PersonBtn *btn;
    BOOL isReplace;
    UIView *personTag;
}
@property (strong, nonatomic) UIScrollView *bgScroll;
@property (strong, nonatomic) UIImageView *blackView;
@property (strong, nonatomic) UIButton *cancel;
@property (strong, nonatomic) UIButton *done;
@property (strong, nonatomic) PersonBtn *person;
@property (strong, nonatomic) Edit_addTextView *input;
@property (strong, nonatomic) NSNumber *state;//1表示回到编辑，0表示退出输入框

@end

@implementation AddPersonViewController

- (void)getWindowImg:(UIImage *)img personArray:(NSArray *)personArray
{

    if (personArray.count > 0) {
        self.personArray = [[NSMutableArray alloc] initWithArray:personArray];
    } else {
        self.personArray = [[NSMutableArray alloc] init];
    }
}
- (void)viewDidLoad {
    [super viewDidLoad];
//    self.personArray = [[NSMutableArray alloc] init];
    isReplace = NO;
    self.title = @"标注";
    self.state = [NSNumber numberWithBool:YES];
    self.navigationController.navigationBar.translucent = NO;
    self.navigationController.navigationBar.backgroundColor = [UIColor whiteColor];
    self.view.backgroundColor = [UIColor colorWithRed:0.969f green:0.973f blue:0.973f alpha:1.00f];
    
    self.cancel = [UIButton buttonWithType:UIButtonTypeCustom];
    [_cancel setImage:[UIImage imageNamed:@"backButton"] forState:UIControlStateNormal];
    _cancel.frame = CGRectMake(0, 0, 30, 30);
    [_cancel addTarget:self action:@selector(cancelController:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:_cancel];
    UIBarButtonItem *backItem = [[UIBarButtonItem alloc] initWithCustomView:_cancel];
    self.navigationItem.leftBarButtonItem = backItem;
    
    self.done = [UIButton buttonWithType:UIButtonTypeCustom];
    [_done setImage:[UIImage imageNamed:@"done"] forState:UIControlStateNormal];
    _done.frame = CGRectMake(self.view.frame.size.width - 0, 0, 30, 30);
    [_done addTarget:self action:@selector(doneController:) forControlEvents:UIControlEventTouchUpInside];
//    [self.view addSubview:_done];
    UIBarButtonItem *doneItem = [[UIBarButtonItem alloc] initWithCustomView:_done];
    self.navigationItem.rightBarButtonItem = doneItem;
    _done.hidden = YES;
    // Do any additional setup after loading the view.
    
    [self createSubViews];
}
- (void)cancelController:(UIButton *)sender
{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)doneController:(UIButton *)sender
{
    [[NSNotificationCenter defaultCenter] postNotificationName:@"addPerson" object:_personArray];
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)createSubViews
{
    self.bgScroll = [[UIScrollView alloc] initWithFrame:self.view.bounds];
    _bgScroll.contentSize = CGSizeMake(0, self.view.bounds.size.height);
    _bgScroll.delegate = self;
    _bgScroll.scrollEnabled = NO;
    [self.view addSubview:_bgScroll];
    NSArray *arrayOne = [NSArray arrayWithObjects:@"人声",@"创作者",@"图像",@"吉他",@"贝斯",@"鼓",@"键盘",@"管乐器",@"弦乐器",@"民族乐器", nil];
    personTag = [[UIView alloc]initWithFrame:CGRectMake(0, 0, self.view.frame.size.width,106*3)];
    
    for (int i = 0; i < 10; i++) {
        self.person = [[PersonBtn alloc] initWithFrame: CGRectMake((0.33125 * self.view.frame.size.width+1) * (i % 3), (0.33125 * self.view.frame.size.width+1) * (i / 3), 0.33125 * self.view.frame.size.width, 0.33125 * self.view.frame.size.width)];
        self.person.backgroundColor = [UIColor whiteColor];

        self.person.isSelected = [NSNumber numberWithBool:NO];
        self.person.personTitle.text = arrayOne[i];
        
        self.person.tag = 10 + i;
        [_person addTarget:self action:@selector(addPersons:) forControlEvents:UIControlEventTouchUpInside];
        
        [_bgScroll addSubview:self.person];
        _person.content.delegate = self;
        [_person.content addTarget:self action:@selector(textFieldDidEditingChanged:) forControlEvents:UIControlEventEditingChanged];
    }
    if (_personArray.count > 0) {
        [self reloadView:_personArray];
    }
}
- (void)reloadView:(NSArray *)personArray
{
    for (NSDictionary *dic in personArray) {
        NSNumber *num = [dic valueForKey:@"key"];
        NSInteger tag = num.integerValue + 10;
        PersonBtn *button = (PersonBtn *)[self.view viewWithTag:tag];
        button.grayline.hidden = NO;
        button.content.text = [dic valueForKey:@"name"];
    }
}
- (void)cancelTextview:(UIButton *)sender
{
    [_input.textView resignFirstResponder];
    _input.hidden = YES;
    btn.grayline.hidden = YES;
    oldTag = 0;
}
- (void)doneTextview:(PersonBtn *)sender
{
    if (sender.content.text.length > 0) {
        sender.grayline.hidden = NO;
        NSNumber *num = [NSNumber numberWithInteger:sender.tag - 10];
        NSDictionary *dic = [NSDictionary dictionaryWithObjectsAndKeys:sender.content.text,@"name", num, @"key", nil];
        if (_personArray.count != 0) {
            for (NSDictionary *dict in _personArray) {
                NSNumber *nums = [dict valueForKey:@"key"];
                if (num == nums) {
                    [_personArray removeObject:dict];
                    [_personArray addObject:dic];
                    isReplace = YES;
                    break;
                }
            }
            if (isReplace == NO) {
                [_personArray addObject:dic];
            }
            isReplace = NO;
        } else {
            [_personArray addObject:dic];
        }
    } else {
        for (NSDictionary *dict in _personArray) {
            NSNumber *number = [dict valueForKey:@"key"];
            if (number.integerValue == sender.tag - 10) {
                [_personArray removeObject:dict];
                sender.grayline.hidden = YES;
                break;
            }
        }
        //btn.personTitle.frame = CGRectMake(0, 0, btn.frame.size.width, btn.frame.size.height);
        //btn.content.frame = CGRectZero;
    }
//    [_input.textView resignFirstResponder];
//    _input.hidden = YES;
//    NSLog(@"%@", _personArray);
}
- (void)addPersons:(PersonBtn *)sender{
    [[UIApplication sharedApplication].keyWindow endEditing:YES];

    [self changeBgScroll];
}
- (BOOL)textFieldShouldReturn:(UITextField *)textField
{
    [textField resignFirstResponder];
    PersonBtn *_btn = (PersonBtn *)textField.superview;
    [self doneTextview:_btn];
    [self changeBgScroll];
    _done.hidden = NO;
    return YES;
}
- (void)textFieldDidBeginEditing:(UITextField *)textField
{
    _done.hidden = YES;
    PersonBtn *_btn = (PersonBtn *)textField.superview;
    if (_btn.tag > 15) {
        [_bgScroll setContentOffset:CGPointMake(0, 0.33125 * self.view.frame.size.width * 2) animated:YES];
    }
}

- (void)textFieldDidEditingChanged:(UITextField *)textField
{
//    [textField.text enumerateSubstringsInRange:NSMakeRange(0, [textField.text length]) options:NSStringEnumerationByComposedCharacterSequences usingBlock:^(NSString *substring, NSRange substringRange, NSRange enclosingRange, BOOL *stop) {
//        const unichar hs = [substring characterAtIndex:0];
//        if (0xd800 <= hs && hs <= 0xdbff) {
//            if (substring.length > 1) {
//                const unichar ls = [substring characterAtIndex:1];
//                const int uc = ((hs - 0xd800) * 0x400) + (ls - 0xdc00) + 0x10000;
//                if (0x1d000 <= uc && uc <= 0x1f77f) {
//                    [textField deleteBackward];
//                }
//            }
//        } else if (substring.length > 1) {
//            const unichar ls = [substring characterAtIndex:1];
//            if (ls == 0x20e3) {
//                [textField deleteBackward];
//            }
//        } else {
//            if (0x2100 <= hs && hs <= 0x27ff) {
//                [textField deleteBackward];
//            } else if (0x2B05 <= hs && hs <= 0x2b07) {
//                [textField deleteBackward];
//            } else if (0x2934 <= hs && hs <= 0x2935) {
//                [textField deleteBackward];
//            } else if (0x3297 <= hs && hs <= 0x3299) {
//                [textField deleteBackward];
//            } else if (hs == 0xa9 || hs == 0xae || hs == 0x303d || hs == 0x3030 || hs == 0x2b55 || hs == 0x2b1c || hs == 0x2b1b || hs == 0x2b50) {
//                [textField deleteBackward];
//            }
//        }
//    }];

}

- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string
{
    if ([[[textField textInputMode] primaryLanguage] isEqualToString:@"emoji"] || ![[textField textInputMode] primaryLanguage]) {
        return YES;
    } else {
        return YES;
    }
}
- (void)changeBgScroll
{
    if (_bgScroll.contentOffset.y >= 0.33125 * self.view.frame.size.width * 2 - 10) {
        _bgScroll.contentOffset = CGPointMake(0, 0);
    }
}
- (BOOL)isBlankString:(NSString *)string
{
    if (string == nil) {
        return NO;
    }
    if (string == NULL) {
        return NO;
    }
    if ([string isKindOfClass:[NSNull class]]) {
        return NO;
    }
    if ([[string stringByTrimmingCharactersInSet:[NSCharacterSet whitespaceAndNewlineCharacterSet]]  length] == 0) {
        return NO;
    }
    return YES;
}

- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}


@end
